import * as THREE from 'three'
import Experience from './Experience'
import { EventEmitter } from 'events'

export default class Assets extends EventEmitter {
    constructor(assets) {
        super();
        this.experience = new Experience();
        this.assets = assets;
        // 资源字典
        this.items = {};

        // 资源加载总数
        this.queue = this.assets.length;

        // 已加载总数
        this.loadedNumber = 0;

        this.create();
    }

    create() {
        // console.log(this.experience);
        for (const asset of this.assets) {
            if (asset.type === 'fileLoader') {
                this.experience.fileLoader.load(
                    asset.path,
                    file => {
                        this.loaded(asset, file);
                    }
                )
            } else if (asset.type === 'textureLoader') {
                const texture = this.experience.textureLoader.load(asset.path)
                this.loaded(asset, texture)
            } else if (asset.type === 'fontLoader') {
                this.experience.fontLoader.load(
                    asset.path,
                    font => {
                        this.loaded(asset, font);
                    }
                )
            } else if (asset.type === 'gltfLoader') {
                this.experience.gltfLoader.load(
                    asset.path,
                    gltf => {
                        this.loaded(asset, gltf.scene);
                    }
                )
            }
        }
    }

    loaded(asset, file) {
        this.items[asset.name] = file;
        this.loadedNumber++;
        console.log('当前资源加载数量', this.loadedNumber +'/' + this.queue);
        if (this.loadedNumber === this.queue) {
            console.log('加载完毕');
            this.emit("ready");
        }
    }
}